# -*- coding: utf-8 -*-

# Define your item pipelines here
#
# Don't forget to add your pipeline to the ITEM_PIPELINES setting
# See: https://docs.scrapy.org/en/latest/topics/item-pipeline.html

import os


class ShanbeiPipeline(object):

    def __init__(self):
        if not hasattr(self, "base_dir"):
            self.base_dir = os.path.dirname(os.path.realpath(__file__))
            pass
        print("base_dir:", self.base_dir)
        pass

    def process_item(self, item, spider):
        # print(item)
        if not os.path.exists(os.path.join(self.base_dir, item['bookname'])):
            os.mkdir(os.path.join(self.base_dir, item['bookname']))
            pass
        with open(os.path.join(self.base_dir, item['bookname'], item['name']), 'a+') as file:
            for (english, chinese) in zip(item['word_english'], item['word_chinese']):
                english = english.strip()
                chinese = chinese.strip().replace("\n", " ^ ")
                # print(english, chinese)
                file.write("%s  # %s \n" % (english, chinese))
                pass
            pass
        return item
